﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using Infragistics.WebUI.UltraWebGrid;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using System.Drawing;
using System.Web.UI;

public partial class MaterialAppForm : ShopfloorPage, INormalReport
{
    const string QueryWhere = "MaterialAppForm";
    uMESCommonBusiness common = new uMESCommonBusiness();
    uMESContainerBusiness containreBal = new uMESContainerBusiness();
    uMESContainerPrintBusiness bll = new uMESContainerPrintBusiness();
    uMESDispatchBusiness dispatch = new uMESDispatchBusiness();
    uMESMaterialBusiness material = new uMESMaterialBusiness();

    protected void Page_Load(object sender, EventArgs e)
    {
        uMESMasterPage master = this.Master as uMESMasterPage;
        master.strNavigation = "当前位置：物料申请";
        master.strTitle = "物料申请";
        master.ChangeFrame(true);
        NormalReportControl normalCntrl = new NormalReportControl();
        normalCntrl.LtnFirst = lbtnFirst;
        normalCntrl.LtnLast = lbtnLast;
        normalCntrl.LtnNext = lbtnNext;
        normalCntrl.LtnPrev = lbtnPrev;
        normalCntrl.BtnReset = btnReSet;
        normalCntrl.BtnGo = btnGo;
        normalCntrl.BtnSearch = btnSearch;
        normalCntrl.LabPages = lLabel1;
        normalCntrl.TxtPage = txtPage;
        normalCntrl.TxtTotalPage = txtTotalPage;
        normalCntrl.TxtCurrentPage = txtCurrentPage;
        normalCntrl.NormalOperation = this;
        normalCntrl.QueryWhere = QueryWhere;

        WebPanel = WebAsyncRefreshPanel1;

        if (!IsPostBack)
        {
            ClearMessage_PageLoad();
        }
    }

    #region 数据查询

    #region 重置
    protected void btnReSet_Click(object sender, EventArgs e)
    {
        ClearDispData();
    }
    #endregion
    public Dictionary<string, string> GetQuery()
    {
        string strScanContainerName = txtScan.Text.Trim();
        string strProcessNo = txtProcessNo.Text.Trim();
        string strContainerName = txtContainerName.Text.Trim();
        string strProductName = txtProductName.Text.Trim();
        string strSpecName = txtSpecName.Text.Trim();
        string strStartDate = txtStartDate.Value.Trim();
        string strEndDate = txtEndDate.Value.Trim();

        Dictionary<string, string> result = new Dictionary<string, string>();
        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
        string strTeamID = userInfo["TeamID"];
       // result.Add("TeamID", strTeamID);
        result.Add("DispatchType", "1");//任务指派
        //result.Add("Status", "0,25"); //已派到班组，或者已经申请,暂移除状态，谁接收谁申请
        result.Add("ScanContainerName", strScanContainerName);
        result.Add("ProcessNo", strProcessNo);
        result.Add("ContainerName", strContainerName);
        result.Add("ProductName", strProductName);
        result.Add("SpecName", strSpecName);
        result.Add("StartDate", strStartDate);
        result.Add("EndDate", strEndDate);
        result.Add("Sequence", "1");//add:Wangjh 0925
        result.Add("ReceiveEmployeeID", userInfo["EmployeeID"]);//add:Wangjh 1124 谁接收谁申请
        result.Add("CurrentStepID","1");
        result.Add("RawMaterial", txtRawMaterial.Text);//原材料信息

        Session[QueryWhere] = result;

        return result;
    }

    public void QueryData(Dictionary<string, string> query)
    {
        ClearMessage();

        uMESPagingDataDTO result = dispatch.GetMaterialAppData(query, Convert.ToInt32(this.txtCurrentPage.Text), 9);
        this.ItemGrid.DataSource = result.DBTable;
        this.ItemGrid.DataBind();
        this.txtTotalPage.Text = result.PageCount;
        if (result.RowCount == "0")
        {
            this.txtCurrentPage.Text = "0";
        }
        lLabel1.Text = string.Format("第 {0} 页  共 {1} 页", this.txtCurrentPage.Text, this.txtTotalPage.Text);
        this.txtPage.Text = this.txtCurrentPage.Text;

        ClearDispData();
    }

    protected void ItemGrid_DataBound(object sender, EventArgs e)
    {
        for (int i = 0; i < ItemGrid.Rows.Count; i++)
        {
            string strSpecName = ItemGrid.Rows[i].Cells.FromKey("SpecName").Text;
            ItemGrid.Rows[i].Cells.FromKey("SpecNameDisp").Text = common.GetSpecNameWithOutProdName(strSpecName);
        }
    }

    public void ResetQuery()
    {
        ClearMessage();

        Session[QueryWhere] = "";
        txtScan.Text = string.Empty;
        txtProcessNo.Text = string.Empty;
        txtContainerName.Text = string.Empty;
        txtProductName.Text = string.Empty;
        txtSpecName.Text = string.Empty;
        txtStartDate.Value = string.Empty;
        txtEndDate.Value = string.Empty;
        ItemGrid.Rows.Clear();

        this.txtTotalPage.Text = "";
        this.txtCurrentPage.Text = "";
        this.txtPage.Text = "";
        lLabel1.Text = "第  页  共  页";
    }
    #endregion

    #region 分页按钮
    protected void lbtnFirst_Click(object sender, EventArgs e)
    {

    }
    protected void lbtnPrev_Click(object sender, EventArgs e)
    {

    }
    protected void lbtnNext_Click(object sender, EventArgs e)
    {

    }
    protected void lbtnLast_Click(object sender, EventArgs e)
    {

    }
    protected void btnGo_Click(object sender, EventArgs e)
    {

    }
    #endregion

    #region 选中批次行
    protected void ItemGrid_ActiveRowChange(object sender, RowEventArgs e)
    {
        ClearMessage();

        try
        {
            txtDispProcessNo.Text = string.Empty;
            if (e.Row.Cells.FromKey("ProcessNo").Value != null)
            {
                string strProcessNo = e.Row.Cells.FromKey("ProcessNo").Text;
                txtDispProcessNo.Text = strProcessNo;
            }

            txtDispOprNo.Text = string.Empty;
            if (e.Row.Cells.FromKey("OprNo").Value != null)
            {
                string strOprNo = e.Row.Cells.FromKey("OprNo").Text;
                txtDispOprNo.Text = strOprNo;
            }

            string strContainerName = e.Row.Cells.FromKey("ContainerName").Text;
            txtDispContainerName.Text = strContainerName;
            string strContainerID = e.Row.Cells.FromKey("ContainerID").Text;
            txtDispContainerID.Text = strContainerID;

            string strProductName = e.Row.Cells.FromKey("ProductName").Text;
            txtDispProductName.Text = strProductName;
            string strProductID = e.Row.Cells.FromKey("ProductID").Text;
            txtDispProductID.Text = strProductID;

            txtDispDescription.Text = string.Empty;
            if (e.Row.Cells.FromKey("Description").Value != null)
            {
                string strDescription = e.Row.Cells.FromKey("Description").Text;
                txtDispDescription.Text = strDescription;
            }

            string strQty = e.Row.Cells.FromKey("Qty").Text;
            txtDispQty.Text = strQty;

            string strSpec = e.Row.Cells.FromKey("SpecNameDisp").Text;
            txtDispSpecName.Text = strSpec;
            string strWorkflowID = e.Row.Cells.FromKey("WorkflowID").Text;
            txtDispWorkflowID.Text = strWorkflowID;
            string strSpecID = e.Row.Cells.FromKey("SpecID").Text;
            txtDispSpecID.Text = strSpecID;

            string strTeamName = e.Row.Cells.FromKey("TeamName").Text;
            txtDispTeamName.Text = strTeamName;
            string strTeamID = e.Row.Cells.FromKey("TeamID").Text;
            txtDispTeamID.Text = strTeamID;

            string strResourceName = string.Empty;
            if (e.Row.Cells.FromKey("ResourceName").Value != null)
            {
                strResourceName = e.Row.Cells.FromKey("ResourceName").Text;
            }
            txtDispResourceName.Text = strResourceName;

            string strResourceID = string.Empty;
            if (e.Row.Cells.FromKey("ResourceID").Value !=null)
            {
               strResourceID= e.Row.Cells.FromKey("ResourceID").Text;
            }
            txtDispResourceID.Text = strResourceID;

            DataTable DT = dispatch.GetResourceDispatchInfo(strResourceID);

            wgDispatchList.DataSource = DT;
            wgDispatchList.DataBind();

            txtDispPlannedCompletionDate.Text = string.Empty;
            if (e.Row.Cells.FromKey("PlannedCompletionDate").Value != null)
            {
                string strPlannedCompletionDate = e.Row.Cells.FromKey("PlannedCompletionDate").Text;
                strPlannedCompletionDate = Convert.ToDateTime(strPlannedCompletionDate).ToString("yyyy-MM-dd");
                txtDispPlannedCompletionDate.Text = strPlannedCompletionDate;
            }

            string strID = e.Row.Cells.FromKey("ID").Text;
            txtDispID.Text = strID;
            string strParentID = e.Row.Cells.FromKey("ParentID").Text;
            txtDispParentID.Text = strParentID;

            string strParentQty = e.Row.Cells.FromKey("ParentQty").Text;
            txtParentQty.Text = strParentQty;

            txtDispMfgOrderName.Text = string.Empty;
            if (e.Row.Cells.FromKey("MfgOrderName").Value != null)
            {
                string strMfgOrderName = e.Row.Cells.FromKey("MfgOrderName").Text;
                txtDispMfgOrderName.Text = strMfgOrderName;
            }

            return;

            DataTable dtEmployee = dispatch.GetEmployeeByDispatchID(strID);
            wgEmployee.DataSource = dtEmployee;
            wgEmployee.DataBind();

            wgProductNo.Clear();
            DataTable dt = dispatch.GetProductNoByDispatchID(strID);

            wgProductNo.DataSource = dt;
            wgProductNo.DataBind();

           
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    #endregion

    #region 物料申请前验证 add:Wangjh 20201019

    Tuple<string, bool> CheckData(UltraGridRow row,bool isCheckApp) {
        Tuple<string, bool> re = new Tuple<string, bool>("",true);

       // var activeRow = ItemGrid.DisplayLayout.ActiveRow;
        if (row == null)
        {
            re = new Tuple<string, bool>("请选择要申请物料的任务", false);
            return re;
        }
        string dispatchId = txtDispID.Text;

        if (isCheckApp) {
            DataTable dt = containreBal.GetTableInfo("materialappinfo", "dispatchinfoid", dispatchId);

            if (dt.Rows.Count > 0)
            {
                if (dt.Rows[0]["issenderp"].ToString() == "5")
                {
                    re = new Tuple<string, bool>("此记录已有物料申请记录,且反馈成功", false);
                    return re;
                }
                else if (dt.Rows[0]["issenderp"].ToString() == "0") {
                    re = new Tuple<string, bool>("此记录已有物料申请记录,请等待集成处理", false);
                    return re;
                }

            }
        }     
        return re;
    }

    #endregion

    #region 物料申请按钮
    protected void btnMaterialApp_Click(object sender, EventArgs e)
    {
        ClearMessage();

        try
        {
            var re = CheckData(ItemGrid.DisplayLayout.ActiveRow,true);

            if (!re.Item2) {
                DisplayMessage(re.Item1, false);
                return;
            }

            Dictionary<string, string> popupData = new Dictionary<string, string>();
            popupData.Add("ID", txtDispID.Text);
            popupData.Add("ProcessNo", txtDispProcessNo.Text);
            popupData.Add("ContainerID", txtDispContainerID.Text);
            popupData.Add("ContainerName", txtDispContainerName.Text);
            popupData.Add("ProductID", txtDispProductID.Text);
            popupData.Add("ProductName", txtDispProductName.Text);
            popupData.Add("Description", txtDispDescription.Text);
            popupData.Add("Qty", txtDispQty.Text);
            popupData.Add("SpecName", txtDispSpecName.Text);
            popupData.Add("SpecID", txtDispSpecID.Text);
            popupData.Add("ResourceName", txtDispResourceName.Text);
            popupData.Add("PlannedCompletionDate", txtDispPlannedCompletionDate.Text);
            popupData.Add("MfgOrderName", txtDispMfgOrderName.Text);
            popupData.Add("WorkflowID", txtDispWorkflowID.Text);

            Session["PopupData"] = popupData;
            
            string strScript = "<script>openmaterialapp()</script>";
            Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    protected void ClearDispData()
    {
        txtDispProcessNo.Text = string.Empty;
        txtDispOprNo.Text = string.Empty;
        txtDispContainerName.Text = string.Empty;
        txtDispProductName.Text = string.Empty;
        txtDispDescription.Text = string.Empty;
        txtDispQty.Text = string.Empty;
        txtDispSpecName.Text = string.Empty;
        txtDispTeamName.Text = string.Empty;
        txtDispResourceName.Text = string.Empty;
        txtDispPlannedCompletionDate.Text = string.Empty;
        txtDispMfgOrderName.Text = string.Empty;
        txtRawMaterial.Text = string.Empty;

        txtDispID.Text = string.Empty;

        wgEmployee.Clear();
        wgProductNo.Clear();
        wgDispatchList.Clear();
    }

    //零件物料申请 add:Wanjh 0925
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            ResultModel pop = GenerateRawMaterialApp();
            if (pop.IsSuccess == false)
            {
                DisplayMessage(pop.Message, false);
            }
            else {
                Session["PopupData"] = pop.Data as DataTable;

                string script = "<script>openMaterialRawApp()</script>";
                Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, script);
            }
            return;

            var activeRow = ItemGrid.DisplayLayout.ActiveRow;

            if (activeRow == null) {
                DisplayMessage("请选择记录", false);
                  return;
            }

            Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
            Dictionary<string, string> para = new Dictionary<string, string>();
            string strID = Guid.NewGuid().ToString();
            string strMaterialAppInfoName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            para.Add("MaterialAppInfoID", strID);
            para.Add("MaterialAppInfoName", strMaterialAppInfoName);
            para.Add("DispatchInfoID", activeRow.Cells.FromKey("ID").Text);
            para.Add("ContainerID", activeRow.Cells.FromKey("ContainerID").Text);
            para.Add("ContainerName", activeRow.Cells.FromKey("ContainerName").Text);
            para.Add("SpecID", activeRow.Cells.FromKey("SpecID").Text);
            para.Add("SpecNo", "");
            para.Add("SpecName", "");
            para.Add("FactoryID", userInfo["FactoryID"]);
            para.Add("ProcessNo", activeRow.Cells.FromKey("ProcessNo").Text);
            para.Add("OprNo", "");
            para.Add("Type", "0");
            para.Add("SubmitEmployeeID", userInfo["EmployeeID"]);

            para.Add("MfgorderName", activeRow.Cells.FromKey("MfgOrderName").Text);
            para.Add("ProductID", activeRow.Cells.FromKey("ProductID").Text);
            para.Add("Qty", activeRow.Cells.FromKey("Qty").Text);
            para.Add("WorkflowID", activeRow.Cells.FromKey("WorkflowID").Text);

            string strSubmitDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            para.Add("SubmitDate", strSubmitDate);
            para.Add("Status", "0");
            para.Add("Notes", ""); para["AppType"] = "0";

            Session["PopupData"] = para;

            string strScript = "<script>openMaterialRawApp()</script>";
            Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);

            //if (material.AddMaterialAppInfo(para, new DataTable()))
            //{
            //    QueryData(GetQuery());
            //    DisplayMessage("提交成功", true);
            //}
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    /// <summary>
    /// 零件物料申请，可能批量申请
    /// </summary>
    /// <returns></returns>
    ResultModel GenerateRawMaterialApp() {
        ResultModel re = new ResultModel(false,"");
        DataTable dt = uMESCommonFunction.GetGridChooseInfo2(ItemGrid, null, "ckSelect");
        if (dt.Rows.Count == 0) {
            return new ResultModel(false,"请选择记录");
        }
        string rawMaterial = "";
        foreach (DataRow row in dt.Rows) {
            //判断是否已经申请过
            if (row["issenderp"].ToString() == "0") {
                return new ResultModel(false, "批次："+row["Containername"].ToString()+"已经申请，请等待集成处理");
            }
            //
            if (rawMaterial == "")
                rawMaterial = row["RawMaterial"].ToString();
            else
            {
                if (rawMaterial != row["RawMaterial"].ToString()) {
                   return new ResultModel(false, "只能同时申请同原材料的任务");
                }
            }
        }
        re.IsSuccess = true;re.Data = dt;
        return re;
    }
    #endregion

    protected void txtScan_TextChanged(object sender, EventArgs e)
    {
        ClearMessage();

        try
        {
            string strScan = txtScan.Text.Trim();
            txtScan.Text = "";

            if (strScan != string.Empty)
            {
                Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
                string strTeamID = userInfo["TeamID"];
                Dictionary<string, string> para = new Dictionary<string, string>();
                para.Add("ScanContainerName", strScan);
                para.Add("TeamID", strTeamID);
                para.Add("DispatchType", "1");
                para.Add("Status", "20"); //已接收

                Session[QueryWhere] = para;

                txtCurrentPage.Text = "1";
                QueryData(para);
            }
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    protected void wgDispatchList_DataBound(object sender, EventArgs e)
    {
        for (int i = 0; i < wgDispatchList.Rows.Count; i++)
        {
            string strSpecName = wgDispatchList.Rows[i].Cells.FromKey("SpecName").Text;
            wgDispatchList.Rows[i].Cells.FromKey("SpecNameDisp").Text = common.GetSpecNameWithOutProdName(strSpecName);
        }
    }

    protected void btnAssort_Click(object sender, EventArgs e)
    {
        ClearMessage();

        try
        {
            var re = CheckData(ItemGrid.DisplayLayout.ActiveRow,false );

            if (!re.Item2)
            {
                DisplayMessage(re.Item1, false);
                return;
            }

            Dictionary<string, string> popupData = new Dictionary<string, string>();
            popupData.Add("ID", txtDispID.Text);
            popupData.Add("ProcessNo", txtDispProcessNo.Text);
            popupData.Add("ContainerID", txtDispContainerID.Text);
            popupData.Add("ContainerName", txtDispContainerName.Text);
            popupData.Add("ProductID", txtDispProductID.Text);
            popupData.Add("ProductName", txtDispProductName.Text);
            popupData.Add("Description", txtDispDescription.Text);
            popupData.Add("Qty", txtDispQty.Text);
            popupData.Add("SpecName", txtDispSpecName.Text);
            popupData.Add("SpecID", txtDispSpecID.Text);
            popupData.Add("ResourceName", txtDispResourceName.Text);
            popupData.Add("PlannedCompletionDate", txtDispPlannedCompletionDate.Text);
            popupData.Add("MfgOrderName", txtDispMfgOrderName.Text);
            popupData.Add("WorkflowID", txtDispWorkflowID.Text);

            Session["PopupData"] = popupData;

            string strScript = "<script>openmaterialapp('1')</script>";
            Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }



    protected void Button2_Click(object sender, EventArgs e)
    {
        try
        {
            ClearMessage();

            UltraGridRow uldr = ItemGrid.DisplayLayout.ActiveRow;
            if (uldr == null)
            {
                DisplayMessage("请选择订单记录", false);
                //Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, "<script>alert('请选择批次记录')</script>");
                return;
            }

            DataTable poupDt = new DataTable();
            poupDt.Columns.Add("ProductID");
            poupDt.Columns.Add("WorkflowID");
            DataRow newRow = poupDt.NewRow();
            newRow["ProductID"] = uldr.Cells.FromKey("ProductID").Text;
            newRow["WorkflowID"] = uldr.Cells.FromKey("Workflowid").Text;
            poupDt.Columns.Add("ContainerID"); poupDt.Columns.Add("ContainerName");
            newRow["ContainerID"] = uldr.Cells.FromKey("ContainerID").Text;
            newRow["ContainerName"] = uldr.Cells.FromKey("ContainerName").Text;
            poupDt.Rows.Add(newRow);
            Session.Add("ProcessDocument", poupDt);
            string strScript = string.Empty;

            strScript = "<script>window.showModalDialog('Custom/bwCommonPage/uMESDocumentViewPopupForm.aspx', '', 'dialogWidth: 700px; dialogHeight: 600px; status = no; center: Yes; resizable: NO; ')</script>";
            Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }


    protected void btnSelectAll_Click(object sender, EventArgs e)
    {
        if (btnSelectAll.Text == "全选")
        {
            btnSelectAll.Text = "全不选";
            uMESCommonFunction.ResetGridCheckStatus(ItemGrid, "ckSelect", 0);
        }
        else if (btnSelectAll.Text == "全不选")
        {
            btnSelectAll.Text = "全选";
            uMESCommonFunction.ResetGridCheckStatus(ItemGrid, "ckSelect", 2);
        }

    }

    protected void btnInRevert_Click(object sender, EventArgs e)
    {
        uMESCommonFunction.ResetGridCheckStatus(ItemGrid, "ckSelect", 1);
    }
}